﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using WebEntities;
using WebEntities.Models.ProductInfo;
using com.subb.ProductInformation;

namespace WebsiteAdmin.Controllers
{
    [Authorize]
    public class ProductController : Controller
    {
        private const string PRODUCTCOVER_PATH = "ProductCover/";

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAllProductByPage(int? cataId, StoreRequestParameters parms)
        {
            PP_ProductDAL pdal = new PP_ProductDAL();
            PP_ProductCataDAL pcdal = new PP_ProductCataDAL();
            int ttlCount;
            List<PP_Product> pprodlist;
            if (cataId.HasValue)
            {
                pprodlist = pdal.GetAllProduct(cataId.Value, parms.Start, parms.Limit, out ttlCount);
            }
            else
            {
                pprodlist = pdal.GetAllProduct(parms.Start, parms.Limit, out ttlCount);
            }
            List<Product> prodList = new List<Product>();
            foreach (var pprod in pprodlist)
            {
                string pcataName = string.Empty;
                if (pprod.ProdCataID.HasValue && pprod.ProdCataID.Value > 0)
                {
                    PP_ProductCata pcata = pcdal.GetProductCata(pprod.ProdCataID.Value);
                    pcataName = pcata.ProdCataName;
                }
                Product prod = Product.AsProduct(pprod, pcataName);
                prodList.Add(prod);
            }
            return this.Store(prodList, ttlCount);
        }

        [HttpPost]
        public ActionResult DeleteProduct(List<Product> delProds)
        {
            try
            {
                PP_ProductDAL pdal = new PP_ProductDAL();
                foreach (var prod in delProds)
                {
                    pdal.RemoveProduct(prod.ProductID);
                }
                return this.Direct(new { Success = true, Msg = "删除成功！" });
            }
            catch (Exception ex)
            {
                return this.Direct(new { Success = false, Msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message });
            }
        }

        public ActionResult NewProductWindow()
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "新建产品",
                Width = 700,
                Height = 500,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.TextListBullets,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("CreateProduct"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Render();
            return this.Direct();
        }

        public ActionResult CreateProduct()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateProduct(Product prod)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            try
            {
                string pdescr = Server.HtmlEncode(prod.Description);
                prod.Description = pdescr;
                string creator = Request.IsAuthenticated ? HttpContext.User.Identity.Name : "Anonymous";
                prod.Creator = creator;
                PP_ProductDAL pdal = new PP_ProductDAL();
                int pid = pdal.CreateProduct(prod);
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("ProductCover");
                    string savePath = string.Empty;
                    //上传产品封面图
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + PRODUCTCOVER_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += pid + extName;
                            fpfb1.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + PRODUCTCOVER_PATH + pid + extName;
                            Product updProd = Product.AsProduct(pdal.GetProduct(pid), "");
                            updProd.ProductCover = webpath;
                            pdal.UpdateProduct(pid, updProd);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "产品创建成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        public ActionResult EditProductWindow(int prodId)
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "编辑产品",
                Width = 700,
                Height = 500,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.TextListBullets,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("EditProduct"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Loader.Params.Add(new Parameter("prodId", prodId.ToString()));
            wnd.Render();
            return this.Direct();
        }

        public ActionResult EditProduct(int prodId)
        {
            PP_ProductDAL pdal = new PP_ProductDAL();
            PP_Product pprod = pdal.GetProduct(prodId);
            if (pprod != null)
            {
                pprod.Description = Server.HtmlDecode(pprod.Description);
            }
            Product product = Product.AsProduct(pprod, "");
            //为了分开代码，不在这里加载图片列表，而是用Proxy，在另外的controller里面加载
            //加载产品图片列表
            //PP_ProductImgDAL pidal = new PP_ProductImgDAL();
            //List<PP_ProductImg> ppimgList = pidal.GetAllProductImg(prodId);
            //List<ProductImg> pimgList = new List<ProductImg>();
            //foreach (var ppimg in ppimgList)
            //{
            //    ProductImg pimg = ProductImg.AsProductImg(ppimg);
            //    pimgList.Add(pimg);
            //}
            //ViewData["ProductImgList"] = pimgList;
            return View(product);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditProduct(Product prod)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            try
            {
                string pdescr = Server.HtmlEncode(prod.Description);
                prod.Description = pdescr;
                PP_ProductDAL pdal = new PP_ProductDAL();
                pdal.UpdateProduct(prod.ProductID, prod);
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("ProductCoverFile");
                    string savePath = string.Empty;
                    //上传产品封面图
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + PRODUCTCOVER_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += prod.ProductID + extName;
                            fpfb1.SaveAs(savePath);
                            //更新路径
                            string webpath = uploadVFolder + PRODUCTCOVER_PATH + prod.ProductID + extName;
                            Product updProd = Product.AsProduct(pdal.GetProduct(prod.ProductID), "");
                            updProd.ProductCover = webpath;
                            pdal.UpdateProduct(prod.ProductID, updProd);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "产品更新成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        public ActionResult ProductDescription(int? prodId)
        {
            if (prodId.HasValue && prodId.Value > 0)
            {
                PP_ProductDAL pdal = new PP_ProductDAL();
                PP_Product pprod = pdal.GetProduct(prodId.Value);
                if (pprod != null)
                {
                    string pdescr = Server.HtmlDecode(pprod.Description);
                    pdescr = pdescr ?? string.Empty;
                    pdescr = pdescr.Replace("\r\n", "<br />");
                    pdescr = pdescr.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
                    ViewBag.ProductDescr = pdescr;
                }
            }
            return View();
        }
    }
}
